package DramCore
{
	// From ru.as3.net
	import flash.events.EventDispatcher;
	import flash.display.Loader;
	import flash.net.URLRequest;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.system.ApplicationDomain;
	import flash.system.SecurityDomain;
	import flash.system.LoaderContext;
	import flash.errors.IllegalOperationError;
	
	public class ClassLoader extends EventDispatcher
	{
		private static var urls:Array = [];
		private var loader:ALoader; 
		private var className:String; 
		private var classURL:String;
		private var __class:Class;
		
		public function ClassLoader(classURL:String, className:String)
		{
			this.classURL = classURL;
			this.className = className;
			
			if(	urls[classURL] ){
				loader = urls[classURL];
			} else {
				loader = new ALoader();
       			var context:LoaderContext = new LoaderContext();
        		context.applicationDomain = new ApplicationDomain() ;
				loader.load(new URLRequest(classURL), context);
				urls[classURL] = loader;
			}
			
			if(loader.completed){
				completeHandler();
			} else {
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
				loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			}
		}	
		
		public function getClass():Class
		{
			return __class;
		}
		
		private function completeHandler(e:Event = null):void
		{
			var applicationDomain:ApplicationDomain = ApplicationDomain(loader.contentLoaderInfo.applicationDomain)
			try 
			{
				__class = applicationDomain.getDefinition(className) as Class;
				dispatchEvent(new Event(Event.COMPLETE));
        	}
        	catch(e:Error) 
        	{
            	throw new IllegalOperationError(className + " definition not found in " + classURL);
        	}
		}
		
		private function ioErrorHandler(e:IOErrorEvent):void
		{ 
            	throw new IllegalOperationError("Can't load " + classURL);
		}
	}
}